<template>
  <div class="app-container">
    <el-container style="max-width: 960px">
      <el-header style="margin-top: 10px;height: auto;">
        <el-row>
          <el-input
            v-model="kwInput"
            placeholder="输入手机号或 LID 进行筛选"
            class="input-with-select"
            clearable
            @keyup.native.enter="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
          </el-input>
          <el-button
            type="primary"
            class="el-icon-plus add-btn"
            :disabled="listLoading"
            @click="handleAction('create', '添加')"
          >添加账号
          </el-button>
        </el-row>
      </el-header>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%"
          @sort-change="handleSort"
        >
          <el-table-column prop="_serialized" label="WhatsApp手机号" width="200" />
          <el-table-column prop="lid" label="LID" width="150" />
          <el-table-column prop="platform" label="平台" width="150" />
          <el-table-column prop="create_at" label="创建时间" width="180">
            <template slot-scope="scope">
              <div>{{ scope.row.create_at }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button
                v-show="!scope.row.edit"
                size="mini"
                icon="el-icon-edit"
                type="warning"
                plain
                @click="handleAction('edit', scope.row)"
              >修改
              </el-button>
              <el-button
                v-show="!scope.row.edit"
                size="mini"
                icon="el-icon-delete"
                type="danger"
                plain
                @click="handleAction('delete', scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-show="total>0"
          background
          :current-page="page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>

    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="temp" label-position="left" label-width="120px" :rules="rules">
        <el-form-item label="WhatsApp手机号" prop="_serialized">
          <el-input v-model="temp._serialized" placeholder="请输入WhatsApp手机号" />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            格式示例：1234567890（手机号码，系统会自动处理格式）
          </div>
        </el-form-item>
        <el-form-item label="LID" prop="lid">
          <el-input v-model="temp.lid" placeholder="请输入用户LID" />
        </el-form-item>
        <el-form-item label="平台" prop="platform">
          <el-select v-model="temp.platform" placeholder="请选择平台">
            <el-option label="本地浏览器" value="本地浏览器" />
            <el-option label="云端服务器" value="云端服务器" />
            <el-option label="移动设备" value="移动设备" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" :loading="confirmLoading" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmm'
import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  name: 'Whatsappaccount',
  data() {
    return {
      table_name: 'WhatsappConfig', // 假设后端表名为 WhatsappAccount
      data: [],
      listLoading: false,
      confirmLoading: false,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // 分页
      pagesize: 10,
      page: 1,
      total: 0,
      action: null,
      title: '',
      temp: {
        _serialized: '',
        lid: '',
        platform: '本地浏览器',
        password: ''
      },
      width: '640px',
      innerDialogVisible: false,
      rules: {
        _serialized: [
          { required: true, message: '请输入WhatsApp手机号', trigger: 'blur' },
          { max: 128, message: '手机号长度不能超过128个字符', trigger: 'blur' }
        ],
        lid: [
          { max: 128, message: 'LID长度不能超过128个字符', trigger: 'blur' }
        ],
        platform: [
          { required: true, message: '请选择平台', trigger: 'change' },
          { max: 128, message: '平台名称长度不能超过128个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { max: 128, message: '密码长度不能超过128个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetTemp() {
      this.temp = {
        _serialized: '',
        lid: '',
        platform: '本地浏览器',
        password: ''
      }
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        table_name: this.table_name,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
          this.$message.error('获取数据失败')
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.title = '添加WhatsApp账号'
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.title = `确认要删除账号：${row._serialized}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.title = `修改账号：${row._serialized}`
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.id = row.id
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      if (this.action === 'delete') {
        this.handleDelete()
        return
      }

      this.$refs.form.validate((valid) => {
        if (valid) {
          this.handleSubmit()
        } else {
          return false
        }
      })
    },
    handleSubmit() {
      this.confirmLoading = true
      const _data = Object.assign({}, this.temp)
      _data.table_name = this.table_name

      switch (this.action) {
        case 'create':
          Post(_data).then(response => {
            this.confirmLoading = false
            this.innerDialogVisible = false
            this.getList()
            this.$message.success('添加成功')
          }).catch(err => {
            this.confirmLoading = false
            this.$message.error('添加失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          break
        case 'edit':
          Put(_data.id, _data).then(response => {
            this.confirmLoading = false
            this.innerDialogVisible = false
            this.getList()
            this.$message.success('更新成功')
          }).catch(err => {
            this.confirmLoading = false
            this.$message.error('更新失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          break
      }
    },
    handleDelete() {
      this.confirmLoading = true
      const _data = Object.assign({}, this.temp)
      _data.table_name = this.table_name

      Delete(_data.id, _data).then(response => {
        this.confirmLoading = false
        this.innerDialogVisible = false
        this.getList()
        this.$message.success('删除成功')
      }).catch(err => {
        this.confirmLoading = false
        this.$message.error('删除失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.el-pagination {
  float: right;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.el-form-item {
  margin-bottom: 22px;
}
</style>
